import { dbUtils } from '../core'

export interface StoreShopFoodBindRow {
    id: string
    food_id: string
    store_id: string
    shop_id: string
    status: number
    max: number
    num: number
    is_delete: number
    create_time: number
    update_time: number
}

export const storeShopFoodBindRepository = {
    upsertBatch(rows: StoreShopFoodBindRow[]): void {
        if (!rows || rows.length === 0) return
        dbUtils.transaction(() => {
            const sql = `INSERT INTO store_shop_food_bind (
                id, food_id, store_id, shop_id, status, max, num, is_delete, create_time, update_time
            ) VALUES (
                ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
            )
            ON CONFLICT(id) DO UPDATE SET
                food_id=excluded.food_id,
                store_id=excluded.store_id,
                shop_id=excluded.shop_id,
                status=excluded.status,
                max=excluded.max,
                num=excluded.num,
                is_delete=excluded.is_delete,
                create_time=excluded.create_time,
                update_time=excluded.update_time,
                updated_at=CURRENT_TIMESTAMP`

            for (const r of rows) {
                dbUtils.execute(sql, [
                    r.id, r.food_id, r.store_id, r.shop_id, r.status, r.max, r.num, r.is_delete, r.create_time, r.update_time
                ])
            }
        })
    },

    listByStore(store_id: string, shop_id?: string) {
        if (shop_id) {
            return dbUtils.query(
                `SELECT * FROM store_shop_food_bind WHERE store_id = ? AND shop_id = ? AND is_delete = 0`,
                [store_id, shop_id]
            )
        }
        return dbUtils.query(
            `SELECT * FROM store_shop_food_bind WHERE store_id = ? AND is_delete = 0`,
            [store_id]
        )
    }
}

export default storeShopFoodBindRepository


